﻿$(function () {
    //编辑活动的时候初始化页面
    if (action && action.ActionId && action.ActionId > 0) {
        $("#Actionname").val(action.ActionName);
        $("#Begintime").val(formatTime(new Date(action.Begintime), "yyyy-MM-dd hh:mm"));
        $("#Endtime").val(formatTime(new Date(action.Endtime), "yyyy-MM-dd hh:mm"));
        $("#ActionDesc").val(action.ActionDesc);

        var html = [];
        for (var i = 0; i < action.GroupList.length; i++) {
            var votetype = action.GroupList[i].VoteType;
            html.push("<li name='groupliitem' " + ((i > 0) ? "style='margin-top:15px'" : "") + " tip='" + i + "'>" + ((i > 0) ? "<hr/>" : "") + "");
            html.push("<div style='margin-left: 25px;'>分组名称：<input type='text' style='width:45%' class='input-xlarge Groupname' value='" + action.GroupList[i].Groupname + "'>");
            html.push("<a name='addItem' class='addItem' href='javascript:void(0);'>添加选项</a><a name='removeGroup' class='removeGroup' href='javascript:void(0);'>删除分组</a></div>");
            html.push("<div style='margin-left: 26px;'>");
            html.push("<span>投票范围：<input type='text' class='MinNum' value='" + action.GroupList[i].MinNum + "'> - <input type='text' class='MaxNum' value='" + action.GroupList[i].MaxNum + "' style='padding-right:5px'></span>");
            html.push("<span style='padding-left:25px'>类型：");
            html.push("<input type='radio' id='votetype" + i + "0' " + (votetype == 0 ? "checked='checked'" : "") + " name='votetype" + i + "' value='0' /><label style='display:inline;vertical-align:middle' for='votetype" + i + "0'>文字</label>&nbsp;&nbsp;&nbsp;&nbsp;");
            html.push("<input type='radio' id='votetype" + i + "1' " + (votetype == 1 ? "checked='checked'" : "") + " name='votetype" + i + "' value='1' /><label style='display:inline;vertical-align:middle' for='votetype" + i + "1'>图文</label>&nbsp;&nbsp;&nbsp;&nbsp;");
            html.push("<input type='radio' id='votetype" + i + "2' " + (votetype == 2 ? "checked='checked'" : "") + " name='votetype" + i + "' value='2' /><label style='display:inline;vertical-align:middle' for='votetype" + i + "2'>视频</label></span></div>");
            html.push("<div style='margin-left: 25px;'>分组介绍：<input type='text'  name='groupdesc' style='width:70%' class='input-xlarge' value='" + action.GroupList[i].GroupDesc + "'>");
            html.push("<div><ul class='item' name='optionlistul'>");

            var isshowuploadimg = (votetype == 0 || votetype == 2 ? "style='display:none'" : "");
            var isshowvideo = (votetype == 0 || votetype == 1 ? "style='display:none'" : "");
            var isshowdesc = (votetype == 0 ? "style='display:none'" : "");

            for (var j = 0; j < action.GroupList[i]["VoteResult"].length; j++) {
                var voteItem = action.GroupList[i]["VoteResult"][j];
                html.push("<li name='optionItemli'><div>");
                html.push("选项名称：<input type='text' class='input-xlarge Itemname' style='width:70%' value='" + voteItem.ItemName + "'><a name='removeItem' class='removeItem'>删除选项</a>");
                html.push("</div>");

                html.push("<div name='uploaddiv' " + isshowuploadimg + ">");
                html.push("上传图片：<input type='file' name='btnfile' class='input-xlarge Imageurl' style='width:70%' value='' onchange='previewImage(this)'> <input type='hidden' name='uploadimgname' value='" + voteItem.ImageUrl + "' /><br />");

                var imgurl = (voteItem.ImageUrl && voteItem.ImageUrl.length > 0) ? "/upload/" + voteItem.ImageUrl : "/ResStatic/Images/noimage.png";
                html.push("<div name='preview' style=' margin-left: 70px;margin-bottom: 10px;'><img name='imghead' width=300 height=149 border=0 src='" + imgurl + "' /></div></div>");

                var videourl = (voteItem.Videourl && (voteItem.Videourl.length > 0)) ? (videourl = "http://v.youku.com/v_show/id_" + voteItem.Videourl + ".html") : "";
                html.push("<div name='videodiv'  " + isshowvideo + " >视频地址：<input name='videourl' type='text' class='input-xlarge Videourl' style='width:70%' value='" + videourl + "' placeholder='请输入优酷视频地址'></div>");

                html.push("<div name='votedescdiv' " + isshowdesc + ">选项描述：<textarea name='votedesc'  rows='3' class='input-xlarge votedesc' style='width:70%'>" + voteItem.Desc + "</textarea></div>");
                html.push("</li>");
            }
            html.push("</ul></div></li>");

            $("#grouplist").html(html.join(""));
        }
    }

    // 删除选项
    $("#grouplist").on("click", "a[name=removeItem]", function () {
        var currentli = $(this).parents('li[name=optionItemli]');
        var allcount = currentli.parents('ul[name=optionlistul]').find('li[name=optionItemli]');
        if (allcount.length < 2) {
            dialog({ title: '提示', content: '分组至少有一个选项！', }).show(); return false;
        }
        currentli.remove();
    });

    // 添加选项
    $("#grouplist").on("click", "a[name=addItem]", function () {
        var votetype = $(this).parents("li[name=groupliitem]").find("input:radio[name^=votetype]:checked").val();
        var isshowuploadimg = (votetype == 0 || votetype == 2 ? "style='display:none'" : "");
        var isshowvideo = (votetype == 0 || votetype == 1 ? "style='display:none'" : "");
        var isshowdesc = (votetype == 0 ? "style='display:none'" : "");

        var html = [];
        html.push("<li  name='optionItemli'><div>选项名称：<input type='text' class='input-xlarge Itemname' style='width:70%' value=''><a class='removeItem' name='removeItem'' href='javascript:void(0);'>删除选项</a></div>");
        html.push("<div name='uploaddiv' " + isshowuploadimg + ">上传图片：<input type='file' name='btnfile' class='input-xlarge Imageurl' style='width:70%' value='' onchange='previewImage(this)'> <input type='hidden' name='uploadimgname' value='' /><br />");
        html.push("<div name='preview' style=' margin-left: 70px;margin-bottom: 10px;'><img name='imghead' width=300 height=149 border=0 src='/ResStatic/Images/noimage.png' /></div></div>");

        html.push("<div name='videodiv' " + isshowvideo + ">视频地址：<input name='videourl' type='text' class='input-xlarge Videourl' style='width:70%' value='' placeholder='请输入优酷视频地址'></div>");
        html.push("<div name='votedescdiv' " + isshowdesc + ">选项描述：<textarea rows='3' name='votedesc'  class='input-xlarge votedesc' style='width:70%'></textarea></div></li>");

        //$(this).siblings("ul").append($(this).siblings("ul").children(":first").clone());
        $(this).parents("li[name=groupliitem]").find('ul[name=optionlistul]').append(html.join(""));
    });

    // 删除分组
    $("#grouplist").on("click", "a[name=removeGroup]", function () {
        if ($("li[name=groupliitem]").length == 1) {
            dialog({ title: '提示', content: '投票活动至少有一个分组！', }).show();
            return false;
        }
        $(this).parents('li[name=groupliitem]').remove();
    });


    // 添加分组
    $("#addGroup").on("click", function () {
        var currentli = parseInt($("li[name=groupliitem]").last().attr("tip")) + 1;
        var html = [];
        html.push("<li style='margin-top:15px' tip='" + currentli + "' name='groupliitem'><hr/><div style='margin-left: 25px;'>分组名称：<input type='text' style='width:45%' class='input-xlarge Groupname' value=''><a name='addItem' class='addItem' href='javascript:void(0);'>添加选项</a><a name='removeGroup' class='removeGroup' href='javascript:void(0);'>删除分组</a></div>");
        html.push("<div style='margin-left: 26px;'><span>投票范围：<input type='text' class='MinNum' value='1'> - <input type='text' class='MaxNum' value='2' style='padding-right:5px'></span>");
        html.push("<span style='padding-left:25px'>类型：");
        html.push("<input type='radio' id='votetype" + currentli + "0' checked='checked' name='votetype" + currentli + "' value='0' /><label style='display:inline;vertical-align:middle' for='votetype" + currentli + "0'>文字</label>&nbsp;&nbsp;&nbsp;&nbsp;");
        html.push("<input type='radio' id='votetype" + currentli + "1' name='votetype" + currentli + "' value='1' /><label style='display:inline;vertical-align:middle' for='votetype" + currentli + "1'>图文</label>&nbsp;&nbsp;&nbsp;&nbsp;");
        html.push("<input type='radio' id='votetype" + currentli + "2' name='votetype" + currentli + "' value='2' /><label style='display:inline;vertical-align:middle' for='votetype" + currentli + "2'>视频</label></span></div>");
        html.push("<div style='margin-left: 25px;'>分组介绍：<input type='text'  name='groupdesc' style='width:70%' class='input-xlarge' value=''>");
        html.push("<div><ul class='item' name='optionlistul'>");

        var subhtml = [];
        subhtml.push("<li name='optionItemli'><div>选项名称：<input type='text' class='input-xlarge Itemname' style='width:70%' value=''><a class='removeItem' name='removeItem'>删除选项</a></div>");
        subhtml.push("<div name='uploaddiv' style='display:none'>");
        subhtml.push("上传图片：<input type='file' name='btnfile' class='input-xlarge Imageurl' style='width:70%' value='' onchange='previewImage(this)'> <input type='hidden' name='uploadimgname' value='' /><br />");
        subhtml.push("<div name='preview' style=' margin-left: 70px;margin-bottom: 10px;'><img name='imghead' width=300 height=149 border=0 src='/ResStatic/Images/noimage.png' /></div></div>");
        subhtml.push("<div name='videodiv' style='display:none'>视频地址：<input name='videourl' type='text' class='input-xlarge Videourl' style='width:70%' value='' placeholder='请输入优酷视频地址'></div>");
        subhtml.push("<div name='votedescdiv' style='display:none'>选项描述：<textarea name='votedesc'  rows='3' class='input-xlarge votedesc' style='width:70%'></textarea></div></li>");

        html.push(subhtml.join("") + subhtml.join(""));
        html.push("</ul></div></li>");

        //$(".group").append($(".group li:first").clone());
        $("#grouplist").append(html.join(""));
    });

    var t1 = null;
    var iscomplated = true;
    //保存
    $("#saveAction").on("click", function () {
        if (t1 == null) { t1 = new Date().getTime(); } else {
            var t2 = new Date().getTime(); if (t2 - t1 < 500) { t1 = t2; return; } else { t1 = t2; }
        }
        if (!iscomplated) { return; }
        var jsonObject = getVoteJson();

        //编辑
        if (action && action.ActionId && action.ActionId > 0) {
            jsonObject["ActionId"] = action.ActionId;
            jsonObject["GroupIds"] = action.GroupIds;
        }

        if (jsonObject && jsonObject.GroupList) {
            var isneedToUpload = false;
            for (var i = 0; i < jsonObject.GroupList.length; i++) {
                if (jsonObject.GroupList[i].VoteType == "1") {
                    isneedToUpload = true;
                    break;
                }
            }
            if (isneedToUpload) {
                // 上传图片
                $('#UpLoadForm').ajaxSubmit({
                    success: function (html, status) {
                        saveAction(jsonObject);
                    }
                });
            } else {
                saveAction(jsonObject);
            }
        }
    });



    function saveAction(jsonObject) {
        iscomplated = false;
        $.ajax({
            type: "POST",
            url: "/Setting/SaveAction",
            contentType: "application/json",
            data: JSON.stringify(jsonObject),
            dataType: "json",
            success: function (data) {
                if (data.RetCode > 0) {
                    dialog({
                        title: "提示", width: "10em", height: "1em", content: "保存成功！",
                        onclose: function () { self.location.href = "/Setting/ActionManager/"; }
                    }).show();
                } else {
                    dialog({
                        title: "提示", width: "10em", height: "1em", content: "保存失败"
                    }).show();
                }
            }
        }).always(function () {
            iscomplated = true;
        });
    }

    // 投票类型切换
    $("#grouplist").on("click", "input:radio[name^=votetype]", function () {
        var currentli = $(this).parents("li[name=groupliitem]");
        var votetype = $(this).val();
        var uploaddiv = currentli.find("div[name=uploaddiv]");
        var videodiv = currentli.find("div[name=videodiv]");
        var votedescdiv = currentli.find("div[name=votedescdiv]");
        if (votetype == 0) {
            uploaddiv.hide();
            videodiv.hide();
            votedescdiv.hide();
        } else if (votetype == 1) {
            uploaddiv.show();
            videodiv.hide();
            votedescdiv.show();
        } else if (votetype == 2) {
            uploaddiv.hide();
            videodiv.show();
            votedescdiv.show();
        }

    });

    // 对Date的扩展，将 Date 转化为指定格式的String 
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
    // 例子： 
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
    function formatTime(date, fmt) { //author: meizz 
        var o = {
            "M+": date.getMonth() + 1,                 //月份 
            "d+": date.getDate(),                    //日 
            "h+": date.getHours(),                   //小时 
            "m+": date.getMinutes(),                 //分 
            "s+": date.getSeconds(),                 //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds()             //毫秒 
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
});


